<!--
 * @Date: 2023-03-04 15:26:32
 * @LastEditors: Zireael 1193875164@qq.com
 * @LastEditTime: 2023-04-10 15:27:24
 * @FilePath: \A19\frontend\src\components\Lv3_source.vue
-->
<template>
  <div id="Lv3_source" class="list-container">
    <div class="head">
      {{ courseId === currentUser._id?'我的':'课程' }}资源
      <div>
        <ElButton v-if="poss"  @click="newFolder">新建文件夹</ElButton>
        <UploadFile v-if="poss" :updateFolder="updateFolder" :path="paths" :course-id="courseId"></UploadFile>
      </div>
    </div>

    <div style="height:calc(100% - 60px)">
      <div style="height:calc(100% - 60px);overflow:auto">
        <div class="breadcrumb-wrapper">
          <el-breadcrumb :separator-icon="ArrowRight" class="breadcrumb">
          <div class="back" @click="backFolder">
            <ElIcon><back /></ElIcon>
          </div>
          <el-breadcrumb-item 
            @click="backTo(index)" 
            :key="path" v-for="(path,index) in paths"
            style="cursor: pointer;user-select:none;color:#0f0f0f;'"
            class="bread"
          >{{ path }}</el-breadcrumb-item>
        </el-breadcrumb>
        </div>
        
        <el-scrollbar 
          class="el"
          max-height="580px"
          v-for="folder in currentFolder?.folders" 
          :key="folder" 
          @click="paths.push(folder)"
        >
          <p class="scrollbar-demo-item">
            <div class="info">
              <div class="icon">
                <el-icon><Folder /></el-icon>
              </div>
              <div class="source-cate">{{ folder }}</div>
            </div>
          <div class="btns">
            <ElButton v-if="poss"  plain style="float: right;" @click.stop="renameFolder(folder)">重命名</ElButton>
            <ElButton v-if="poss"  type="danger" plain style="float: right;" @click.stop="deleteFolder(folder)">删除</ElButton>
          </div>
          </p>
        </el-scrollbar>

        <el-scrollbar 
          max-height="580px"
          v-for="file in currentFolder?.files" 
          :key="file.url" 
          @click="accseeToFile(file.url,file.name)"
        >
          <p class="scrollbar-demo-item">
            <div class="info">
              <div class="icon">
                <el-icon><Document /></el-icon>
              </div>
              <div class="source-cate">
                <a :href="'./#/file?url=' + file.url  + '&name=' + file.name" target="_blank" @click.stop="">{{ file.name }}</a>
              </div>
            </div>
          <div class="btns">
            <ElButton v-if="poss"  type="primary" plain style="float: right;" @click.stop="download(file.url)">下载</ElButton>
            <ElButton v-if="poss"  plain style="float: right;" @click.stop="reNameFile(file.name)">重命名</ElButton>
            <ElButton v-if="poss"  type="danger" plain style="float: right;" @click.stop="deleteFile(file.url)">删除</ElButton>
          </div>
          </p>
        </el-scrollbar>
      </div>
    </div>
  
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, watch, defineProps, inject, Ref, computed } from 'vue';
import { ArrowRight } from '@element-plus/icons-vue'
import { useClientStore } from '../pinia/stores/client';
import { ResNewFolder } from '@/shared/protocols/SourceManage/PtlNewFolder';
import { conf } from '@/utils/conf';
import { storeToRefs } from 'pinia';
import { useRoute, useRouter } from 'vue-router';
interface file{
  name:string
  url:string
}

const store= useClientStore()
const {currentUser} = store
const route = useRoute()
const router = useRouter()
const {currentCourseId} = storeToRefs(store)

// const poss = inject<Ref<boolean>>('poss')
const poss = computed(() =>{
  return Boolean(!(route.params.courseId as string) || currentUser.role === 'teacher')
})
const courseId = (route.params.courseId as string) || currentUser._id
if(route.params.courseId){
  currentCourseId.value = route.params.courseId as string
}
const client = useClientStore().client
const paths = reactive(['root'])
const currentFolder = ref< {
  folders:Array<string>,
  files:Array<file>
}>()

let loadingInstance:any
const newFolder = async () =>{
  try {
    const name = await ElMessageBox.prompt('文件夹名')
    loadingInstance = ElLoading.service({
      target:'#app',
    })
    const ret = await client.callApi('SourceManage/NewFolder',{
      course:courseId,
      name:name.value,
      path:paths
    })
    updateFolder(ret)
  } catch (error) {
  }
}
const deleteFolder = async (folder:string)=>{
  try {
    await ElMessageBox.confirm('确定删除吗')
    loadingInstance = ElLoading.service({
      target:'#app',
    })
    const ret = await client.callApi('SourceManage/DeleteFolder',{
      path:paths,
      name:folder,
      course:courseId
    })
    updateFolder(ret)
  } catch (error) {
  }
}
const renameFolder = async (folder:string) =>{
  try {
    const newName = await ElMessageBox.prompt('重命名',{
      inputValue:folder
    })
    loadingInstance = ElLoading.service({
      target:'#app',
    })
    const ret = await client.callApi('SourceManage/RenameFolder',{
      path:paths,
      name:folder,
      rename:newName.value,
      course:courseId
    })
    updateFolder(ret)
  } catch (error) {
  }
}
const deleteFile = async (url:string)=>{
  try {
    await ElMessageBox.confirm('确定删除吗')
    loadingInstance = ElLoading.service({
      target:'#app',
    })
    const ret = await client.callApi('SourceManage/DeleteFile',{
      path:paths,
      url,
      course:courseId
    })
    updateFolder(ret)
  } catch (error) {
  }
}
const reNameFile = async (name:string) =>{
  try {
    const newName = await ElMessageBox.prompt('重命名',{
      inputValue:name,
    })
    loadingInstance = ElLoading.service({
      target:'#app',
    })
    const ret = await client.callApi('SourceManage/RenameFile',{
      path:paths,
      course:courseId,
      name,
      newName:newName.value
    })
    updateFolder(ret)
  } catch (error) {
  }
}

const download = (url:string)=>{
  // console.log(url);
  self.open(conf.server + url + '?download=true')
}
const accseeToFile = (url:string,name:string)=>{
  self.open('./#/file?url=' + url + '&name=' + name)
}
const backTo = (index:number)=>{
  console.log(index);
  // paths.splice(index,)
  paths.length = index + 1
}
const updateFolder = (ret:{
  isSucc:boolean,
  res?:{
    folders:string[],files:file[]
  }
})=>{
  if(ret.isSucc){
    ElMessage.success('操作成功')
    currentFolder.value = ret.res
  }
  loadingInstance.close()
}
const backFolder = () =>{
  if(paths.length > 1) paths.pop()
}



watch(paths,async newValue =>{
  loadingInstance = ElLoading.service({
    target:'#app',
  })
  const ret = await client.callApi('SourceManage/GetPathFiles',{
    path:newValue,
    course:courseId
  })
  if(ret.isSucc){
    currentFolder.value = ret.res
  }
  loadingInstance.close()
},{immediate:true})

onMounted(async ()=>{
  const courseId = route.params.courseId as string
  
  if(!courseId) {
    ElMessage.error('不存在')
    router.back()
    return
  }
  
  currentCourseId.value = courseId
})
</script>

<style lang="less" scoped>
#navi {
  width: 1350px;
  height: 6vh;
  background-color: rgb(236, 197, 255);
  // text-align: center;
  line-height: 5vh;
}

.scrollbar-demo-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 80px;
  margin: 5px;
  text-align: center;
  border-radius: 4px;
  background: rgb(250, 249, 249);
  &:hover{
    background: rgb(246, 246, 246);
    .info .source-cate{
      text-decoration: underline;
    }
  }
  color: var(--el-color-primary);
  cursor: pointer;
  .info{
    display: flex;
    justify-content: space-between;
    align-items: center;
    .icon{
      font-size: 46px;
      margin-left: 20px;
      margin-right: 15px;
    }
    .source-cate{
      a{
        color:var(--el-color-primary);
        text-decoration: none;
      }
    }
  }
  .btns{
    margin-right: 20px;
    display: flex;
  }
}
.breadcrumb-wrapper{
  position: sticky;
  top: 0px;
  z-index: 100;
  padding-bottom: 5px;
  padding-top: 5px;
  background: white;
}
.breadcrumb{
  padding: 5px 5px;
  margin: 0px 5px 0px 5px;
  /* margin-bottom: -5px; */
  line-height: 30px;
  background: #faf9f9;
  .back{
    display: inline-block;
    color: #606266;
    float: left;
    line-height: 30px;
    font-size: 20px;
    width: 40px;
    text-align: center;
    transform: translateY(3px);
    cursor: pointer;
  }
  .bread{
    
  }
}
.el{
  height: auto;
}
</style>